import { io, Socket } from "socket.io-client";
import  { log} from "../logManager";
import _ from "lodash";

export class BaseSocketIo {
  ioInstance: Socket;
  uri;

  constructor(
    uri,
    opts = {
      autoConnect: true, // 自动连接
    },
  ) {
    this.uri = uri;
    this.ioInstance = io(uri, opts);
    this.listenConnectEvents();
  }

  connect(): void {
    this.ioInstance.connect();
  }

  listenConnectEvents(): void {
    this.ioInstance.on("connect", () => {
      log.log(`${this.uri},socket io connected`);
    });

    this.ioInstance.on("disconnect", () => {
      log.log(`${this.uri},socket io disconnect`);
    });

    this.ioInstance.on(
      "connect_error",
      _.throttle((e) =>{
        log.error(this.uri,"connect error",e.message);
      }, 60 * 1000)
    );
  }
}
